"""
同步: sync time.sleep 阻塞程序的执行，效率低
    同步请求库 requests
异步: async
    防止耗时任务（网络请求，数据IO操作）阻挡后续任务的执行
"""
import time
import requests
import asyncio
import aiohttp


# 同步请求 10个url案例
# urls = [f'https://httpbin.org/get?age={i}' for i in range(10)]

# start = time.time()
# for url in urls:
#     res = requests.get(url)
#     print(res.json())
#
# end = time.time() - start
# print(f"时间消耗", end)



# 异步基础结构
# async def main():
#     """
#     异步函数中需要有耗时任务  await（等待耗时操作结束）
#     返回协程
#     使用asyncio.run() 启动携程
#     """
#     print(1)
#     await asyncio.sleep(1)
#     print(2)
#
# main_task = main()
#
# r = asyncio.run(main_task)
# print(r)







# 多个异步任务并行执行
# async def task1(param):
#     print(param, 'start1')
#     await asyncio.sleep(3)
#     print(param, 'end1')
#
# async def task2(param):
#     print(param, 'start2')
#     await asyncio.sleep(5)
#     print(param, 'end2')
#
#
# async def main():
#     await asyncio.gather(task1(100), task2(200))
#
# start = time.time()
# asyncio.run(main())
# end = time.time()
# print(f"时间开销", end-start)



# 执行 相似任务
# async def task(name):
#     await asyncio.sleep(1)
#     print(f'task {name} 完成')
#
#
# async def main():
#     tasks = [task(i) for i in range(10)]
#     await asyncio.gather(*tasks)
#
# asyncio.run(main())




# async def main():
#     # 异步上下文
#     async with aiohttp.ClientSession() as session:
#         # 发起请求
#         async with session.get('https://httpbin.org/get?age=1') as response:
#             # 等待异步结束 获取结果
#             r = await response.json()
#             print(r)
#     # await asyncio.sleep(1)
#
#
# start = time.time()
#
# # 启动异步任务
# asyncio.run(main())
# print("耗时", time.time()-start)




async def fetch(session, url):
    async with session.get(url) as response:
        return await response.json()


async def main():
    async with aiohttp.ClientSession() as session:
        # gather 并行多个协程  *[task1(), task2()]
        result = await asyncio.gather(*[fetch(session, f'https://httpbin.org/get?age={i}') for i in range(10)])
        for r in result:
            print(r)
    # await asyncio.sleep(1)


start = time.time()
asyncio.run(main())
print("耗时", time.time()-start)